package services

import (
	"errors"
	"fmt"
	"github.com/kataras/iris/v12"
	"huanteng/vendors/crypto/gbcrypt"
	"huanteng/vendors/validator"
	"huanteng/web/middleware"
	"huanteng/web/models"
	"huanteng/web/repositories"
)

const Guard string = "user"
type UserService interface {

	Register(ctx iris.Context) (err error)
	Login(user *models.User) (m map[string]interface{},err error)
	Test()
}

func(s *userService) Test()  {
	fmt.Println("fuck ouyang")
}

type userService struct {
	Repo repositories.UserRepository
}
func NewUserService(repo repositories.UserRepository) UserService {
	return &userService{
			Repo:repo,
		 }
}


func (s *userService) Register(ctx iris.Context) (err error) {
	var user models.User
	var userInfo models.User
	err=validator.ValidateInfo(ctx.ReadJSON(&user))
	if err!=nil{
		return
	}

	userInfo,err=s.Repo.FindByName(user.Name)
	if userInfo !=(models.User{}){
		err=errors.New("用户名已存在")
		return
	}
	userInfo,err=s.Repo.FindByPhone(user.Phone)
	if userInfo !=(models.User{}){
		err=errors.New("手机号已存在")
		return
	}
	user.PassWord,_=gbcrypt.GeneratePassWd(user.PassWord)

	s.Repo.Create(&user)
	return nil
}

func (s *userService) Login(user *models.User) (m map[string]interface{},err error) {
    var userInfo models.User
	userInfo,_=s.Repo.FindByPhone(user.Phone)
	if userInfo ==(models.User{}){
		err=errors.New("手机号不存在")
		return
	}
	_,err=gbcrypt.ValidatePassWd(user.PassWord,userInfo.PassWord);
	if err!=nil{
		return
	}

	token,error:=middleware.GenerateToken(user.ID,Guard)
	if error!=nil{
		return
	}
	//密码不展示
	userInfo.PassWord=""
	m=map[string]interface{}{
		"user":userInfo,
		"token":string(token),
	}

	return
}
